#include <stdio.h>
#include <time.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string.h>
#include <pwd.h>
#include <grp.h>

#define BUFSIZE	16

char file_type(mode_t mode);
char *file_group_name(gid_t gid);
int file_nlink(nlink_t n);
int file_mode(mode_t mode, char *buf, int size);
long file_size(off_t size);
char *file_user_name(uid_t uid);
char *file_mtime(struct timespec st_mtim);

int main(int argc, char *argv[])
{
	struct stat res;
	char str[BUFSIZE] = {};

	if (argc < 2)
		return 1;

	if (-1 == stat(argv[1], &res)) {
		perror("stat()");
		return 1;
	}

	// 文件的类型 权限 res.st_mode
	file_mode(res.st_mode, str, BUFSIZE);
	printf("%c%s %d %s %s %ld %s %s\n", file_type(res.st_mode), str, \
			file_nlink(res.st_nlink), file_user_name(res.st_uid), \
			file_group_name(res.st_gid), file_size(res.st_size), \
			file_mtime(res.st_mtim), argv[1]);

	return 0;
}

// 文件类型
char file_type(mode_t mode)
{
	char res;

	// if ((mode & S_IFMT) == S_IFREG)

	switch (mode & S_IFMT) {
		case S_IFREG:
			res = '-';
			break;
		case S_IFDIR:
			res = 'd';
			break;
			// ... 省略5个case
		default:
			res = '?';
			break;
	}

	return res;
}

int file_mode(mode_t mode, char *buf, int size)
{
	int mode_value[] = {S_IRUSR, S_IWUSR, S_IXUSR, S_IRGRP, \
	S_IWGRP, S_IXGRP, S_IROTH, S_IWOTH, S_IXOTH};
	int i;
	
	if (size < 10)
		return -1;
	strcpy(buf, "rwxrwxrwx");

	for (i = 0; i < 9; i++) {
		if (!(mode & mode_value[i]))
			buf[i] = '-';
	}

	return 0;
}

long file_size(off_t size)
{
	return size;
}

int file_nlink(nlink_t n)
{
	return n;
}

char *file_user_name(uid_t uid)
{
	struct passwd *pw = getpwuid(uid);
	if (NULL == pw)
		return NULL;
	return pw->pw_name;
}

char *file_group_name(gid_t gid)
{
	struct group *gr = getgrgid(gid);
	if (NULL == gr)
		return NULL;
	return gr->gr_name;
}

char *file_mtime(struct timespec st_mtim)
{
	static char buf[BUFSIZE] = {};

	struct tm *tmp = localtime(&st_mtim.tv_sec);
	strftime(buf, BUFSIZE, "%m月 %d %H:%M", tmp);

	return buf;
}




